package com.yunbao.hujin.mymvpcommon.mvp;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;

import com.yunbao.hujin.mymvpcommon.mvp.base.BasePresenter;
import com.yunbao.hujin.mymvpcommon.request.WeatherBean;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * P层-特点:需要持有M层和V层 on 2017/12/7.
 * 4.修改Presenter和Activity中的代码，各自继承自己的基类并去除重复代码
 */

public class RequestPresenter extends BasePresenter<RequestView> {

    private RequestMode mMode;

    public RequestPresenter() {
        this.mMode = new RequestMode();
    }

    /**
     * 处理数据逻辑层
     */
    public void clickRequest(final String cityId) {
        //获取View
        if (getmMvpView() != null) {
            //请求时显示加载
            getmMvpView().requestLoading();
        }

        //模拟耗时，可以展示出loading
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mMode.request(cityId, new Callback<WeatherBean>() {
                    @Override
                    public void onResponse(Call<WeatherBean> call, Response<WeatherBean> response) {
                        //判断View是否为空
                        if (getmMvpView() != null)
                            getmMvpView().resultSuccess(response.body());    //view展示数据
                    }

                    @Override
                    public void onFailure(Call<WeatherBean> call, Throwable t) {
                        if (getmMvpView() != null)
                            getmMvpView().resultFailure(Log.getStackTraceString(t));
                    }
                });
            }
        }, 1000);
    }

    /**
     * 取消网络请求
     */
    public void interruptHttp() {
        mMode.interruptHttp();
    }


    /**
     * 如果界面意外销毁,Presenter可以通过重写以下方法进行释放资源，存储数据，和恢复数据
     * 可以不要
     */
    @Override
    public void onCreatePresenter(@Nullable Bundle saveBundle) {
        super.onCreatePresenter(saveBundle);
        if(saveBundle != null){
            Log.e("perfect-mvp","RequestPresenter5  onCreatePersenter 测试  = " + saveBundle.getString("test2") );
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.e("perfect-mvp","RequestPresenter5  onSaveInstanceState 测试 " );
        outState.putString("test2","test_save2");
    }


    @Override
    public void onDestroyPresenter() {
        super.onDestroyPresenter();
    }


}
